#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <string.h>

int main(int argc, char *argv[])
{
//    int fd = open(argv[1], O_RDONLY);
//    dup2(fd, 0);
//    
//    char buffer[2048];
//    size_t s = read(0, buffer, sizeof(buffer));
//    if(s > 0)
//    {
//        buffer[s] = 0;
//        printf("stdin redir:\n%s\n", buffer);
//    }


    //write(1, "hello 1\n", 8);

    //printf("hello fd: %d\n", fd);
    //fprintf(stdout, "hello fd: %d\n", fd);
    //fputs("hello world\n", stdout);
    //
    //const char *message = "hello fwrite\n";
    //fwrite(message, 1, strlen(message), stdout);


    //close();???

    close(1);                 //为什么close之后加上flush才可以重定向 
    int fd1 = open("log1.txt", O_WRONLY | O_CREAT | O_TRUNC, 0666);
    printf("fd1: %d\n", fd1);
    fprintf(stdout, "helloworld\n");
    //fflush(stdout); //TODO
    close(fd1);//系统调用close；如果不加fflush，这意味着进程还没结束就关闭文件了，还没有缓冲到系统内部
    //fclose(stdout);


//    printf("stdin: %d\n", stdin->_fileno);
//    printf("stdout: %d\n", stdout->_fileno);
//    printf("stderr: %d\n", stderr->_fileno);
//
//    FILE* fp = fopen("log.txt", "w");
//    printf("fp: %d\n", fp->_fileno);
//

   // char buffer[128];
   // ssize_t s = read(0, buffer, sizeof(buffer));
   // if(s > 0)
   // {
   //     buffer[s-1] = 0;
   //     printf("%s\n", buffer);
   // }

    //const char *message = "hello write\n";
    //write(1, message, strlen(message));

    //umask(0);
    //int fd1 = open("log.txt", O_WRONLY | O_CREAT | O_TRUNC, 0666);
    //int fd1 = open("log1.txt", O_WRONLY | O_CREAT | O_APPEND, 0666);
    //int fd2 = open("log2.txt", O_WRONLY | O_CREAT | O_APPEND, 0666);
    //int fd3 = open("log3.txt", O_WRONLY | O_CREAT | O_APPEND, 0666);
    //int fd4 = open("log4.txt", O_WRONLY | O_CREAT | O_APPEND, 0666);
    //if(fd1 < 0)
    //{
    //    perror("open");
    //    return 1;
    //}
    //printf("fd1: %d\n", fd1);
    //printf("fd2: %d\n", fd2);
    //printf("fd3: %d\n", fd3);
    //printf("fd4: %d\n", fd4);

    //const char *message = "aaa\n";
    //write(fd1, message, strlen(message));

    //close(fd1);
    return 0;
}

